package info.batcloud.fanli.core.service.impl;

import com.alibaba.fastjson.JSON;
import info.batcloud.fanli.core.service.SystemSettingService;
import info.batcloud.fanli.core.service.WeixinService;
import info.batcloud.fanli.core.settings.WeixinSetting;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import javax.inject.Inject;
import java.io.IOException;

@Service
public class WeixinServiceImpl implements WeixinService {

    @Override
    public AccessToken auth(String code, String appId, String appSecret) {
        if (StringUtils.isBlank(code)) {
            return null;
        }
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId
                + "&secret=" + appSecret + "&code=" + code + "&grant_type=authorization_code");
        try {
            HttpResponse res = client.execute(httpGet);
            String result = EntityUtils.toString(res.getEntity());
            AccessToken accessToken = JSON.parseObject(result, AccessToken.class);
            return accessToken;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public UserInfo userInfo(String accessToken, String openid) {
        String url = "https://api.weixin.qq.com/sns/userinfo?lang=zh_CN&access_token=" + accessToken + "&openid=" + openid;
        CloseableHttpClient client = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse res = client.execute(httpGet);
            String result = EntityUtils.toString(res.getEntity(), "utf8");
            client.close();
            UserInfo userInfo = JSON.parseObject(result, UserInfo.class);
            return userInfo;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

}
